package testview.zhen.com.myapplication.hencoder.practice_draw2

import android.content.Context
import android.graphics.*
import android.os.Build
import androidx.annotation.RequiresApi
import android.util.AttributeSet
import android.view.View

import testview.zhen.com.myapplication.R


class Practice08XfermodeView : View {

    var paint = Paint(Paint.ANTI_ALIAS_FLAG)
    var bitmap1: Bitmap = BitmapFactory.decodeResource(resources, R.mipmap.batman)
    var bitmap2: Bitmap = BitmapFactory.decodeResource(resources, R.mipmap.batman_logo)

    constructor(context: Context) : super(context) {}

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {}

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {}

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)


        // 使用 paint.setXfermode() 设置不同的结合绘制效果

        // 别忘了用 canvas.saveLayer() 开启 off-screen buffer  可以使底部不是黑色的

        canvas.saveLayer(null,null)//开启off-screen buffer 的步骤1

        //------------------第一个图---------------------------
        canvas.drawBitmap(bitmap1, 0f, 0f, paint)
        // 第一个：PorterDuff.Mode.SRC
        var xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC)
        paint.xfermode = xfermode
        canvas.drawBitmap(bitmap2, 0f, 0f, paint)
        paint.xfermode = null
        //-------------------第二个图---------------------------------
        canvas.drawBitmap(bitmap1, (bitmap1.width + 100).toFloat(), 0f, paint)
        // 第二个：PorterDuff.Mode.DST_IN
        var x1 = PorterDuffXfermode(PorterDuff.Mode.DST_IN)
        paint.xfermode = x1
        canvas.drawBitmap(bitmap2, (bitmap1.width + 100).toFloat(), 0f, paint)
        paint.xfermode =null
        //-------------------第三个图---------------------------------
        canvas.drawBitmap(bitmap1, 0f, (bitmap1.height + 20).toFloat(), paint)
        var x2 = PorterDuffXfermode(PorterDuff.Mode.DST_OUT)
        paint.xfermode = x2
        // 第三个：PorterDuff.Mode.DST_OUT
        canvas.drawBitmap(bitmap2, 0f, (bitmap1.height + 20).toFloat(), paint)
        paint.xfermode = null
        canvas.restore()//关闭off-screen buffer 的步骤
        //开启off-screen buffer 的步骤2
        // 用完之后使用 canvas.restore() 恢复 off-screen buffer
    }
}
